package com.tensquare.article.filter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Component
public class JwtFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器！");

        final String authorHeader = request.getHeader("Authorization");

        Optional.ofNullable(authorHeader)
                .filter(a -> a.startsWith("Bearer "))
                .map(a -> {
                    final String token = authorHeader.substring(7);
                    Claims claims = jwtUtil.parseJWT(token);//鉴权
                    return claims;
                })
                .ifPresent(claims -> {
                    String roles = String.valueOf(claims.get("roles"));
                    request.setAttribute(roles + "_claims", claims);
                });

        return true;
    }
}
